﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using EntityMap.Meta;
using System.Collections;
using EntityMap;
using System.IO;

namespace EntityMap
{
    /// <summary>
    /// This class manage entity metadata information stored on xml files.
    /// </summary>
    public class XmlFileEntityMapRepository : IEntityMapRepository
    {
        private string _mapsFolder = null;

        public string MapsFolder
        {
            get
            {
                return _mapsFolder;
            }            
        }

        public XmlFileEntityMapRepository() {}

        public XmlFileEntityMapRepository( string mapsFolder ) : this()
        {
            _mapsFolder = mapsFolder;
        }

        #region IEntityMapRepository Members

        public EntityInfo GetEntityInfo( Type entityType )
        {
            XmlSerializer serializer = new XmlSerializer( typeof( EntityInfo ) );

            string fileName = String.Empty;

            if( !String.IsNullOrEmpty( _mapsFolder ) )
            {
                fileName = String.Format( @"{0}\{1}.xml", _mapsFolder, entityType.Name );
            }
            else
            {
                fileName = String.Format( "{0}.xml", entityType.Name );
            }

            if( !File.Exists( fileName ) )
            {
                throw new EntityMapException( String.Format( "The {0} file is not exist!", fileName ) );
            }

            using( FileStream fs = new FileStream( fileName, FileMode.Open, FileAccess.Read, FileShare.Read ) )
            {
                return serializer.Deserialize( fs ) as EntityInfo;
            }
        }

        public void SaveEntityInfo( Type entityType, EntityInfo entityInfo )
        {
            XmlSerializer serializer = new XmlSerializer( typeof( EntityInfo ) );

            string fileName = String.Empty;

            if( !String.IsNullOrEmpty( fileName ) )
            {
                fileName = String.Format( @"{0}\{1}.xml", _mapsFolder, entityType.Name );
            }
            else
            {
                fileName = String.Format( "{0}.xml", entityType.Name );
            }

            using( FileStream fs = new FileStream( fileName, FileMode.Create, FileAccess.Write ) )
            {
                serializer.Serialize( fs, entityInfo );
            }
        }

        public Type[] GetEntities()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
